﻿using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using ZYXmeBase.Contracts;
using ZYXmeBase.Dtos;
using ZYXmeBase.Models;
using ZYXmeBase.Services;

namespace ZYXmeBase.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [AllowAnonymous]
    public class AuthController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly IUserService _userService;
        private IConfiguration _configuration;


        public AuthController(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager,
            IConfiguration configuration,
            IUserService userService)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _configuration = configuration;
            _userService = userService;
        }

        [HttpPost("Register")]
        public async Task<IActionResult> Register(UserInfoDto model)
        {
            var newUser = new ApplicationUser { UserName = model.UserName, Email = model.UserName };
            var result = await _userManager.CreateAsync(newUser, model.Password);
            if (!result.Succeeded) return BadRequest(result.Errors);
            return Ok();
        }

        //[HttpPost("Login")]
        //public async Task<IActionResult> Login(UserInfoDto model)
        //{
        //    var signInResult = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);
        //    if (!signInResult.Succeeded) return Unauthorized();
        //    return Ok();
        //}

        [HttpPost("Login")]
        public async Task<IActionResult> Login([FromBody] UserInfoDto user)
        {
            if (user == null)
            {
                return BadRequest("Invalid client request");
            }

            // Here you should check if the user is valid credentials or not, for example by checking in database.

            if (string.IsNullOrWhiteSpace(user.UserName) || string.IsNullOrWhiteSpace(user.Password))
            {
                return BadRequest("账号或密码不能为空");
            }
            var verifyModel = await _userService.Verify(user.UserName, MD5Encrypt.GetMD5(user.Password));
            if (verifyModel != null)
            {
                var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
                var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

                var authClaims = new List<Claim>
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id),
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim("Id", user.Id),
                    new Claim("UserName", user.UserName ?? "")

                };
                var tokenOptions = new JwtSecurityToken(
                    issuer: _configuration["Jwt:Issuer"],
                    audience: _configuration["Jwt:Audience"],
                    claims: authClaims,
                    expires: DateTime.Now.AddMinutes(30),
                    signingCredentials: signinCredentials
                );

                var tokenString = new JwtSecurityTokenHandler().WriteToken(tokenOptions);
                return Ok(new { Token = tokenString });
            }
            else
            {
                return Unauthorized();
            }
        }

        // 可添加更多认证方法，例如：logout、refreshToken等
    }
}
